package com.zhangzhe.httpclienttest.controller;

import com.alibaba.fastjson.JSON;
import com.zhangzhe.httpclienttest.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/test")
public class TestHttpClientController {

    @GetMapping("/testGet")
    public String testGet() {
        return "abcd";
    }

    @GetMapping("/testGetWithParam")
    public String testGetWithParam(@RequestParam(value = "name") String nameaaa, @RequestParam int age) {
        return "name=" + nameaaa + "&age=" + age;
    }

    @PostMapping("/testPost")
    public String testPost() {
        return "无参post请求";
    }

    @PostMapping("/testObjectPost")
    public String testObjectPost(@RequestBody User user) {
        return JSON.toJSONString(user);
    }

    /**
     * 接收表单方式提交来的数据必须去掉@RequestBody注解
     *
     * @param user
     * @return
     */
    @PostMapping("/testForm1Post")
    public String testForm1Post(User user) {
        return JSON.toJSONString(user);
    }

    @PostMapping("/testFile")
    public String testFile(@RequestParam String name, @RequestParam String age
            , @RequestParam("files") List<MultipartFile> multipartFiles) {
        StringBuilder sb = new StringBuilder(64);
        sb.append("name=" + name);
        sb.append("age" + age);
        String fileName;
        for (MultipartFile multipartFile : multipartFiles) {
            sb.append("文件信息");
            fileName = multipartFile.getOriginalFilename();
            if (fileName == null) {
                continue;
            }
            try {
                sb.append("文件名：" + URLDecoder.decode(fileName, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sb.append(multipartFile.getContentType());
        }
        return sb.toString();
    }

    @PostMapping("/is")
    public String testStreamPost(@RequestParam String name, InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder(64);
        String line;
        while (true) {
            try {
                if (!((line = bufferedReader.readLine()) != null)) {
                    sb.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
